package model

import (
	"07demo-gin-mongodb/mongodb"
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"time"
)

type User struct {
	Name string
	Age  int
	City string
}
type Users struct {
	Collection *mongo.Collection
	UserInfo   map[string](*User)
}

func insertOne(collection *mongo.Collection) {
	user1 := User{"one", 11, "1 City"}
	insertResult, err := collection.InsertOne(context.TODO(), user1)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Inserted a single document: ", insertResult.InsertedID)
}
func insertOne2() {
	user1 := User{"one", 11, "1 City"}
	insertResult, err := mongodb.UserCollection.InsertOne(context.TODO(), user1)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Inserted a single document: ", insertResult.InsertedID)
}

func SelectOne(name string) {
	filter := bson.D{{"name", name}}
	fmt.Println("filter:", filter)

	var result User

	err := mongodb.UserCollection.FindOne(context.TODO(), filter).Decode(&result)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found a single document: %+v\n", result)
}

func List(users []User, page int64) ([]User, int64, error) {
	filter := bson.D{{"Name", 1}}
	fmt.Println("filter:", filter)
	var limit int64 = 0
	ctx, cannel := context.WithTimeout(context.Background(), time.Minute)
	defer cannel()
	var findoptions *options.FindOptions
	if limit > 0 {
		findoptions.SetLimit(limit)
		findoptions.SetSkip(limit * page)
	}
	cur, err := mongodb.UserCollection.Find(ctx, bson.M{}, findoptions)
	//count, err := mongodb.UserCollection.CountDocuments(ctx.TO, filter)
	count, err := mongodb.UserCollection.CountDocuments(context.TODO(), bson.M{})

	if err != nil {
		fmt.Println("Find: ", err)
	}
	defer cur.Close(context.Background())
	err = cur.All(context.Background(), &users)

	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found a single document: %+v\n", users)
	return users, count, err
}
